package com.hzspace.ribbon;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@EnableHystrix
@RestController
@EnableEurekaClient//服务被注册中心发现 只能是Eureka注册中心
@EnableDiscoveryClient//服务被注册中心发现 可以是其他注册中心
@SpringBootApplication
public class RibbonApplication {

    public static void main(String[] args) {
        SpringApplication.run(RibbonApplication.class, args);
    }


    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Autowired
    RestTemplate restTemplate;


    //回滚方法//超时设置//设置熔断//断路器的最小请求数,//休眠时间//断路频率
    @HystrixCommand(fallbackMethod = "hiError",
            commandProperties = {
                @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds" , value = "5000"),
                @HystrixProperty(name="circuitBreaker.enabled" , value = "true"),
                @HystrixProperty(name="circuitBreaker.requestVolumeThreshold" , value = "10"),
                @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds" , value = "10000"),
                @HystrixProperty(name="circuitBreaker.errorThresholdPercentage" , value = "60")
            }
    )
    @GetMapping(value = "/hi")
    public String hi(@RequestParam String name) {
        return restTemplate.getForObject("http://EUREKA-CLIENT/hi?name="+name,String.class);
    }


    public String hiError(String name) {
        return "hi,"+name+",sorry,system busy!";
    }
}
